package com.k.kc.cryptojava;

import com.k.kc.util.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.spec.KeySpec;

/**
 * @author ljw
 */
public class DESUtils {
    private static final String ALGORITHM_TYPE = "DES";
    private static final String ENCRYPT_MODEL = "DES/ECB/PKCS5Padding";
    private static final String CHARSET = "utf-8";

    private static Key genDESKey(String keyStr) throws Exception {
        KeySpec keySpec = new DESKeySpec(keyStr.getBytes(CHARSET));
        return SecretKeyFactory.getInstance(ALGORITHM_TYPE).generateSecret(keySpec);
    }
    private static byte[] encrypt(Key key,String content) throws Exception{
        Cipher cipher = Cipher.getInstance(ENCRYPT_MODEL);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(content.getBytes(CHARSET));
        return encrypted;
    }
    private static byte[] decrypt(Key key,String content) throws Exception{
        Cipher cipher = Cipher.getInstance(ENCRYPT_MODEL);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(ByteUtils.fromBase64(content, StandardCharsets.UTF_8));
        return decrypted;
    }

    private static String encryptDES(String keyStr,String content) throws Exception {
        Key key = genDESKey(keyStr);
        byte[] encrypted = encrypt(key,content);
        return ByteUtils.toBase64(encrypted);
    }
    private static String decryptDES(String keyStr,String content) throws Exception{
        Key key = genDESKey(keyStr);
        byte[] decrypted = decrypt(key,content);
        return ByteUtils.toStr(decrypted,"utf-8");
    }


    public static void main(String[] args) {
        try {
            /**
             msg:3721 Encrypt:WrYcMC7Sj3U=
             msg:WrYcMC7Sj3U= Decrypt:3721
             */
            // DES Encrypt
            String keyStr = "1qaz2wsx3edc4rfv";
            String msg = "3721";
            String encryptedStr = DESUtils.encryptDES(keyStr,msg);
            System.out.println("msg:"+msg + " Encrypt:"+ encryptedStr);

            // DES Decrypt
            String decryped = DESUtils.decryptDES(keyStr,encryptedStr);
            System.out.println("msg:"+encryptedStr + " Decrypt:"+ decryped);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
